//
//  HYBaseViewController.m
//  HYNeiHan
//
//  Created by 上官惠阳 on 16/9/25.
//  Copyright © 2016年 上官惠阳. All rights reserved.
//

#import "HYBaseViewController.h"
#import <objc/runtime.h>
#import "NSNotificationCenter+Addition.h"
#import "HYCustomNoNetworkEmptyView.h"
#import "HYCustomLoadingAnimationView.h"
#import "AFNetworkReachabilityManager.h"
#import "YYWebImageManager.h"
#import "YYDiskCache.h"
#import "YYMemoryCache.h"

const char HYBaseTableVcNavRightItemHandleKey;
const char HYBaseTableVcNavLeftItemHandleKey;

@interface HYBaseViewController ()
@property (nonatomic, weak) HYCustomNoNetworkEmptyView *noNetworkEmptyView;
@property (nonatomic, weak) HYCustomLoadingAnimationView *animationView;
@end

@implementation HYBaseViewController
@synthesize navItemTitle = _navItemTitle;
@synthesize navRightItem = _navRightItem;
@synthesize navLeftItem = _navLeftItem;
@synthesize hiddenStatusBar = _hiddenStatusBar;
@synthesize barStyle = _barStyle;
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIView setAnimationsEnabled:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

    // 在自定义leftBarButtonItem后添加下面代码就可以完美解决返回手势无效的情况
    NSArray *gestureArray = self.navigationController.view.gestureRecognizers;
    for (UIGestureRecognizer *gesture in gestureArray) {
        if ([gesture isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
            for (UIView *sub in self.view.subviews) {
                if ([sub isKindOfClass:[UIScrollView class]]) {
                    UIScrollView *sc = (UIScrollView *)sub;
                    [sc.panGestureRecognizer requireGestureRecognizerToFail:gesture];
                }
            }
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [UIView setAnimationsEnabled:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.edgesForExtendedLayout = UIRectEdgeAll;

    self.view.backgroundColor = kBaseBgColor;

    [NSNotificationCenter addObserver:self action:@selector(requestSuccessNotification) name:HYRequestSuccessNotification];
}
- (void)requestSuccessNotification
{
    [self hideLoadingAnimation];
}
- (void)pop
{
    if (self.navigationController == nil) return ;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)popRootVc
{
    if (self.navigationController == nil) return ;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)popToVc:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
    if (self.navigationController == nil) return ;
    [self.navigationController popToViewController:vc animated:YES];
}

- (void)dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dismissWithCompletion:(void(^)())completion
{
    [self dismissViewControllerAnimated:YES completion:completion];
}

- (void)presentVc:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
    [self presentVc:vc completion:nil];
}

- (void)presentVc:(UIViewController *)vc completion:(void(^)(void))completion
{
    if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
    [self presentViewController:vc animated:YES completion:completion];
}

- (void)pushVc:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
    if (self.navigationController == nil) return ;
    if (vc.hidesBottomBarWhenPushed == NO) {
        vc.hidesBottomBarWhenPushed = YES;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)removeChildVc:(UIViewController *)childVc
{
    if ([childVc isKindOfClass:[UIViewController class]] == NO) {
        return ;
    }
    [childVc.view removeFromSuperview];
    [childVc willMoveToParentViewController:nil];
    [childVc removeFromParentViewController];
}

- (void)addChildVc:(UIViewController *)childVc
{
    if ([childVc isKindOfClass:[UIViewController class]] == NO) {
        return ;
    }
    [childVc willMoveToParentViewController:self];
    [self addChildViewController:childVc];
    [self.view addSubview:childVc.view];
    childVc.view.frame = self.view.bounds;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (HYCustomNoNetworkEmptyView *)noNetworkEmptyView {
    if (!_noNetworkEmptyView) {
        HYCustomNoNetworkEmptyView *empty = [[HYCustomNoNetworkEmptyView alloc] init];
        [self.view addSubview:empty];
        _noNetworkEmptyView = empty;

        WeakSelf(weakSelf);
        [empty mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view);
        }];
        empty.customNoNetworkEmptyViewDidClickRetryHandle = ^(HYCustomNoNetworkEmptyView *emptyView) {
            [weakSelf loadData];

        };
    }
    return _noNetworkEmptyView;
}
/** 加载中 **/
- (void)showLoadingAnimation {
    HYCustomLoadingAnimationView *animation = [[HYCustomLoadingAnimationView alloc] init];
    [animation showInView:self.view];
    _animationView = animation;
    [self.view bringSubviewToFront:animation];
}

/** 停止加载 **/
- (void)hideLoadingAnimation
{
    [_animationView dismiss];
    _animationView = nil;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.view bringSubviewToFront:self.animationView];
}
- (void)loadData {
    
}
- (BOOL)isNetworkReachable {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}
/** 设置导航栏右边的item*/
- (void)HY_setUpNavRightItemTitle:(NSString *)itemTitle itemImage:(NSString *)imageName handle:(void(^)(NSString *rightItemTitle))handle{
    [self HY_setUpNavItemTitle:itemTitle itemImage:imageName handle:handle leftFlag:NO];
}

/** 设置导航栏左边的item*/
- (void)HY_setUpNavLeftItemTitle:(NSString *)itemTitle itemImage:(NSString *)imageName  handle:(void(^)(NSString *leftItemTitle))handle {
    [self HY_setUpNavItemTitle:itemTitle itemImage:imageName handle:handle leftFlag:YES];
}

- (void)HY_navLeftItemHandle:(UIBarButtonItem *)item {
    void (^handle)(NSString *) = objc_getAssociatedObject(self, &HYBaseTableVcNavLeftItemHandleKey);
    if (handle) {
        handle(item.title);
    }
}
- (void)HY_navItemRightHandle:(UIBarButtonItem *)item {
    void (^handle)(NSString *) = objc_getAssociatedObject(self, &HYBaseTableVcNavRightItemHandleKey);
    if (handle) {
        handle(item.title);
    }
}
- (void)HY_setUpNavItemTitle:(NSString *)itemTitle itemImage:(NSString *)imageName  handle:(void(^)(NSString *itemTitle))handle leftFlag:(BOOL)leftFlag {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:itemTitle forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn sizeToFit];

    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    if (handle) {
        if (leftFlag) {
            objc_setAssociatedObject(self, &HYBaseTableVcNavLeftItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [btn addTarget:self action:@selector(HY_navLeftItemHandle:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            objc_setAssociatedObject(self, &HYBaseTableVcNavRightItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [btn addTarget:self action:@selector(HY_navItemRightHandle:) forControlEvents:UIControlEventTouchUpInside];
        }

    }
    if (leftFlag) {
        self.navigationItem.leftBarButtonItem = item;
    }else{
        self.navigationItem.rightBarButtonItem = item;
    }

    //    if (itemTitle.length == 0 || !handle) {
    //        if (itemTitle == nil) {
    //            itemTitle = @"";
    //        } else if ([itemTitle isKindOfClass:[NSNull class]]) {
    //            itemTitle = @"";
    //        }
    //        if (leftFlag) {
    //            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];


    //        } else {
    //            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];
    //        }
    //    } else {
    //        if (leftFlag) {
    //            objc_setAssociatedObject(self, &HYBaseTableVcNavLeftItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(HY_navItemHandle:)];

    //        } else {
    //            objc_setAssociatedObject(self, &HYBaseTableVcNavRightItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(HY_navItemHandle:)];
    //        }
    //    }

}

/** 监听通知*/
- (void)HY_observeNotiWithNotiName:(NSString *)notiName action:(SEL)action {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:action name:notiName object:nil];
}

/** 导航栏标题*/
- (void)setNavItemTitle:(NSString *)navItemTitle {
    if ([navItemTitle isKindOfClass:[NSString class]] == NO) return ;
    if ([navItemTitle isEqualToString:_navItemTitle]) return ;
    _navItemTitle = navItemTitle.copy;
    self.navigationItem.title = navItemTitle;
}

- (NSString *)navItemTitle {
    return self.navigationItem.title;
}

/** statusBar是否隐藏*/
- (void)setHiddenStatusBar:(BOOL)hiddenStatusBar {
    _hiddenStatusBar = hiddenStatusBar;
    //更新状态栏
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)hiddenStatusBar {
    return _hiddenStatusBar;
}

- (void)setBarStyle:(UIStatusBarStyle)barStyle {
    if (_barStyle == barStyle) return ;
    _barStyle = barStyle;
    [self setNeedsStatusBarAppearanceUpdate];
}

- (BOOL)prefersStatusBarHidden {
    return self.hiddenStatusBar;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.barStyle;
}

/** 右边item*/
- (void)setNavRightItem:(UIBarButtonItem *)navRightItem {

    _navRightItem = navRightItem;
    self.navigationItem.rightBarButtonItem = navRightItem;
}

- (UIBarButtonItem *)navRightItem {
    return self.navigationItem.rightBarButtonItem;
}
/** 左边item*/
- (void)setNavLeftItem:(UIBarButtonItem *)navLeftItem {

    _navLeftItem = navLeftItem;
    self.navigationItem.leftBarButtonItem = navLeftItem;
}

- (UIBarButtonItem *)navLeftItem {
    return self.navigationItem.leftBarButtonItem;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    [[[YYWebImageManager sharedManager] cache].diskCache removeAllObjects];
    [[[YYWebImageManager sharedManager] cache].memoryCache removeAllObjects];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
